package com.spark.shiro.realm;


import com.spark.shiro.entity.User;
import com.spark.shiro.service.UserService;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Connection;

/**
 * Created by tyd on 2017-10-28.
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        String userName = (String) principalCollection.getPrimaryPrincipal();

        Connection conn;
        try {
            SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
            authorizationInfo.setRoles(userService.getRolesByUserName(userName));
            authorizationInfo.setStringPermissions(userService.getPermissionsByUserName(userName));

            return authorizationInfo;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String userName = (String) authenticationToken.getPrincipal();

        try {
            User user = userService.getUserByUserName(userName);
            if (user != null) {
                return new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), "aa");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
